import { Injectable } from '@nestjs/common';
import { onAuthenticate, Client, Credential, Function } from '@alecmmiller/pigeon-mqtt-nest';
import { createHash, createHmac } from 'node:crypto'


@Injectable()
export class MqttBrokerService {
	constructor(
		//private readonly config:ConfigureService,
	) {
		
	}


	md5(str: string) {
		return createHash('md5').update(str).digest('hex').toLowerCase()
	}

	getSignature(data, key) {
		try {
			const keyBuffer = Buffer.from(key, 'utf8');
			const hmac = createHmac('sha1', keyBuffer);
			hmac.update(data);
			const rawHmac = hmac.digest();

			const signature = Buffer.from(rawHmac).toString('hex');

			return signature;
		} catch (error) {
			console.error(error);
		}
		return null;
	}

	// @onClientDisconnect()
	// OnClientDisconnect(@Client() client) {
	// 	console.log('------OnClientDisconnect----------')
	// 	console.log('------deviceId----------:')
	// 	console.log(client.deviceId, client.id)
	// 	if (client.deviceId) {
	// 		this.updateConnectStatus(client.deviceId, 0)
	// 	}
	// }

	// updateConnectStatus(deviceId: number, status: number) {
	// 	console.log('updateConnectStatus', deviceId)
	// 	let time = Math.floor(Date.now() / 1000)
	// 	this.deviceRepository.update({id : deviceId}, {connectStatus : status, connectTime : time})

	// 	this.cacheManager.store.client.publish(this.config.get('deviceConnectStatusTopic'), JSON.stringify({id:deviceId,status, time}))
	// }


	@onAuthenticate()
	async onAuthenticate(@Client() client, @Credential() credential, @Function() done) {
		if (!credential.username || !credential.password) return done(null, false);

		const username = credential.username

		const password = credential.password.toString().toLowerCase()

		
		if (client.id.startsWith('$$')) {
			if (username.length < 9) throw new Error('username length can not less than 9');
			const p0 = username.slice(0, 4)
			const p1 = username.slice(4, username.length - 4)
			const p2 = username.slice(username.length - 4)

      const res = password == createHash('sha256').update(this.md5(p0) + this.md5(p1) + this.md5(p2)).digest('hex').toLowerCase()

      console.log(res ? '验证通过' : '验证错误')

			return done(null, res);
		}


		return done(null, false)
	}

}